#include "SCENE0917.h"

USING_NS_CC;

Scene * Scene0917::createScene()
{
	return Scene0917::create();
}

bool Scene0917::init()
{
	if (!Scene::init())
	{
		return false;
	}
	visibleSize = Director::getInstance()->getVisibleSize();

	//游戏背景
	Sprite *background = Sprite::create("bg2.jpg");
	background->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
	addChild(background);

	//加载素材
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("GameSence.plist", "GameSence.png");



	//注册触屏事件
	//事件监听器
	EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create();
	listener->onTouchBegan = CC_CALLBACK_2(Scene0917::onTouchBegin, this);
	listener->onTouchMoved= CC_CALLBACK_2(Scene0917::onTouchMoved, this);
	//把这个listener加入到事件派发器里
	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);

	


	//创建4个玩家


	
	

	//关闭游戏场景按钮
	MenuItemImage *closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png");
	closeItem->setCallback(CC_CALLBACK_1(Scene0917::closeItemClicked, this));
	closeItem->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
	closeItem->setPosition(Vec2(-visibleSize.width / 2, visibleSize.height / 2));
	closeItem->setScale(3);


	//开始游戏按钮
	MenuItemFont *beginItem = MenuItemFont::create(CommonFunction::getChineseWithKey("beginGame")->getCString(), 
		CC_CALLBACK_1(Scene0917::beginGame, this));
	Menu *menu = Menu::create(closeItem,beginItem, NULL);

	//Menu *menu = Menu::create(closeItem, NULL);
	addChild(menu);

	self_pos = 1;
	for (int i = 1; i <= 4; i++)
	{
		Player *player = new Player();
		player->account = StringUtils::format("player%d", i);
		player->position = i;
		loadPlayerUI(player);
	}


	//创建赛红十按钮
	Button *showButton = Button::create("show_normal.png");
	showButton->setPosition(Vec2(visibleSize.width / 2-100, visibleSize.height / 2));
	//showButton->setEnabled(false);禁用按钮
	showButton->setVisible(false);//隐藏
	showButton->setTag(100);
	showButton->addTouchEventListener(CC_CALLBACK_2(Scene0917::buttonClicked, this));
	addChild(showButton);


	//创建不赛红十按钮
	Button *unshowButton = Button::create("unShow_normal.png");
	unshowButton->setPosition(Vec2(visibleSize.width / 2+100, visibleSize.height / 2));
	unshowButton->setVisible(false);//隐藏
	unshowButton->setTag(200);
	unshowButton->addTouchEventListener(CC_CALLBACK_2(Scene0917::buttonClicked, this));
	addChild(unshowButton);



	return true;
}

void Scene0917::setRoomId(int roomId)
{
	Label *label = Label::createWithSystemFont(StringUtils::format("room id = %d", roomId), "Arial", 50);
	label->setAnchorPoint(Vec2::ANCHOR_TOP_RIGHT);
	label->setPosition(Vec2(VISIBLE_SIZE.width - 30, VISIBLE_SIZE.height - 30));
	label->enableOutline(Color4B(90, 221, 247, 255), 3);
	addChild(label);
}

void Scene0917::loadPlayerUI(Player * player)
{
	player->pos_char = getPlayerCharPosition(player->position);

	//创建玩家节点包括了该玩家的ui信息等
	player->createPlayerNode();
	addChild(player->node);
	switch (player->pos_char)
	{
	case 's':
		player_self = player;
		break;
	case 'r':
		player_right = player;
		break;
	case 'f':
		player_front = player;
		break;
	case 'l':
		player_lelf = player;
		break;
	default:
		break;
	}

}


//开始游戏
void Scene0917::beginGame(Ref * sender)
{
	CCLOG("gameStar");
	//如果之前有牌，则清除后再开始
	if (game)
	{
		//因为game创建的时候，在构造器里创建了存放自己牌的节点
		game->selfCards_node->removeAllChildrenWithCleanup(true);
		CC_SAFE_DELETE(game);

		//之前的一些残留的内容需要清除
		//比如：上一局赛的红十
		//player_self->node->getChildByTag(2);
		player_self->node->removeChildByTag(2);
		/*player_right->node->removeChildByTag(2);
		player_front->node->removeChildByTag(2);
		player_lelf->node->removeChildByTag(2);*/


	}


	//1.洗牌
	int cards[54];
	game = new CardGame();
	game->gameDidBegan = true;
	game->shuffle(cards, 54);

	//2.发牌
	player_self->initCards();
	player_right->initCards();
	player_front->initCards();
	player_lelf->initCards();
	Player *currentPlayer;//记录当前操作的玩家
	int start_pos = 1;//先发给3号
	for (int i=0;i<54;i++)
	{
		//获取当前发牌者的真实位置
		char pos_char = getPlayerCharPosition((start_pos + i - 1) % 4 + 1);
		
		//红心3
		if (cards[i] == 41)
		{
			game->first = pos_char;
		}
		//方块10
		if (cards[i] == 22)
		{
			game->red10_fk = pos_char;
		}

		//红心10
		if (cards[i] == 48)
		{
			game->red10_hk = pos_char;
		}
		switch (pos_char)
		{
		case 's':
			currentPlayer = player_self;
			break;
		case 'r':
			currentPlayer = player_right;
			break;
		case 'f':
			currentPlayer = player_front;
			break;
		case 'l':
			currentPlayer = player_lelf;
			break;
		
		}
		currentPlayer->cards[i/4] = cards[i];
	}
	//发牌结束位置
	//如果至少有一张红十在我自己这，那需要显示赛与不赛的按钮
	if (game->red10_fk == 's' || game->red10_hk == 's')
	{
		getChildByTag(100)->setVisible(true);
		getChildByTag(200)->setVisible(true);
	}
	else
	{
		//自己没红十
		getChildByTag(100)->setVisible(false);
		getChildByTag(200)->setVisible(false);
	}



	//给自己的牌排序
	player_self->sortCards();

	//计算牌组放置的整体X轴居中位置
	int count = player_self->countCards();
	int mid = count / 2;//中间牌的索引位置
	float midx = (visibleSize.width + 180) / 2;

	//显示自己的牌
	for (int i = 0; i < count; i++)
	{
		//通过0-53的值，获取对应牌的精灵
		Sprite *cardSprite = game->getCardSpritWithValue(player_self->cards[i]);
		cardSprite->setScale(0.9);

		cardSprite->setPosition(Vec2(midx + 60 * (i - mid)+(count%2==0?30:0), cardSprite->getBoundingBox().size.height / 2 + 30));
		cardOriginY= cardSprite->getPositionY();

		//cardSprite->setPosition(Vec2(cardSprite->getBoundingBox().size.width / 2+i*60, visibleSize.height / 2));

		game->selfCards_node->addChild(cardSprite);
	
	}
	addChild(game->selfCards_node);
	

}


void Scene0917::closeItemClicked(Ref * sender)
{
	Director::getInstance()->replaceScene(Scene0910::createScene());
}

//s 表示 self自己
//l 表示 left上家
//r 表示 right下家
//f 表示 front对家
char Scene0917::getPlayerCharPosition(int pos)
{
	if (self_pos == 1)//当自己坐在1上
	{
		if (pos == 2)return 'r';//则2在右边
		if (pos == 3)return 'f';//3在对面
		if (pos == 4)return 'l';//4在左边
	}
	if (self_pos == 2)//当自己坐在2上
	{
		if (pos == 1)return 'l';//1在左边
		if (pos == 3)return 'r';//3在右边
		if (pos == 4)return 'f';//4在对面
	}
	if (self_pos == 3)//当自己坐在3上
	{
		if (pos == 1)return 'f';
		if (pos == 2)return 'l';
		if (pos == 4)return 'r';
	}
	if (self_pos == 4)//当自己坐在4上
	{
		if (pos == 1)return 'r';
		if (pos == 2)return 'f';
		if (pos == 3)return 'l';
	}
	return 's';
}

bool Scene0917::onTouchBegin(Touch * touch, Event * event)
{
	//获取点击的位置
	Vec2 point= touch->getLocation();
	CCLOG("dianjiweizhi：%f,%f", point.x, point.y);

	//前提：牌已经显示出来了
	if (!game || game->gameDidBegan == false)
	{
		return true;
	}
	bool didTouchCard = false;




	//遍历我的每张牌
	int count = player_self->countCards();
	for (int i=0;i<count;i++)
	{
		CCLOG("%d",player_self->cards[i]);
		//获取当前遍历的那张牌的精灵节点
		Node *card_node= game->selfCards_node->getChildByTag(player_self->cards[i]);
		//获取该节点的Rect
		Rect rect = card_node->getBoundingBox();

		//计算左侧区域
		Rect rectForTouch = Rect(rect.origin.x, rect.origin.y, 60, rect.size.height);
		//最后一张牌，接收事件的范围应该是自己整个区域
		if (i==count-1)
		{
			rectForTouch = rect;
		}
		//如何区域内包含了点击的点的位置，则找到了那张被点击的牌
		if (rectForTouch.containsPoint(point))
		{
			//弹出状态，需回到原始Y的位置
			if (card_node->getPositionY()>cardOriginY)
			{
				card_node->setPositionY(cardOriginY);
			}
			else//弹出
			{
				MoveTo *moveCard = MoveTo::create(1, Vec2(card_node->getPositionX(), cardOriginY + 30));
				card_node->runAction(moveCard);
				//card_node->setPositionY(cardOriginY + 30);
			}
			didTouchCard = true;
			break;//找到那张点击的牌了
		}
		
	}
	if (didTouchCard)
	{
		CCLOG("diandaol");
	}
	else
	{
		CCLOG("meiyou");
		for (int i=0;i<count;i++)
		{
			//找到牌，并缩进
			Node *cars_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
			cars_node->setPositionY(cardOriginY);

		}
	}
	return true;
}

void Scene0917::onTouchMoved(Touch * touch, Event * event)
{
	Vec2 point = touch->getLocation();
	CCLOG("shoushiyidong....");
	//前提：牌已经显示出来了
	if (!game || game->gameDidBegan == false)
	{
		return ;
	}


	//遍历我的每张牌
	int count = player_self->countCards();
	for (int i = 0; i<count; i++)
	{
		CCLOG("%d", player_self->cards[i]);
		//获取当前遍历的那张牌的精灵节点
		Node *card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
		//获取该节点的Rect
		Rect rect = card_node->getBoundingBox();

		//计算左侧区域
		Rect rectForTouch = Rect(rect.origin.x, rect.origin.y, 60, rect.size.height);
		//最后一张牌，接收事件的范围应该是自己整个区域
		if (i == count - 1)
		{
			rectForTouch = rect;
		}
		//如何区域内包含了点击的点的位置，则找到了那张被点击的牌
		if (rectForTouch.containsPoint(point))
		{
			
				card_node->setPositionY(cardOriginY + 30);
			
			break;//找到那张点击的牌了
		}

	}
	return ;

}

void Scene0917::buttonClicked(Ref * sender, Widget::TouchEventType type)
{
	CCLOG("anniubeidianji");
	//这里只处理结束的事件
	if (type==Widget::TouchEventType::ENDED)
	{
		Button *btn = (Button *)sender;
		switch (btn->getTag())
		{
		case 100:
		{//赛
			int res = 0;
			if (game->red10_hk == 's'&&game->red10_fk == 's')
			{
				res = 3;
			}
			else if (game->red10_fk == 's')
			{
				res = 1;
			}
			else if (game->red10_hk == 's')
			{
				res = 2;
			}
			player_self->show(res);
			/*player_lelf->show(res);
			player_front->show(res);
			player_right->show(res);*/
			break;
		}
		case 200://不赛
			//player_self->unShow();
			break;
		default:
			break;
		}
		//完成赛红十逻辑后，把按钮隐藏掉
		getChildByTag(100)->setVisible(false);
		getChildByTag(200)->setVisible(false);
	}
}


